import time

import cv2
import numpy as np

from ascript.android import screen
from ascript.android.ui import ImageWindow

class OpenCVTool:

    def find_img(self, img_path, offset=(0, 0), threshold=0.8):
        # 截取屏幕
        bitmap = screen.capture()
        # 将内存截图Bitmap转换为cv img
        img = screen.bitmap_to_cvimage(bitmap)
        return self.is_icon_exist(img, img_path, offset, threshold)

    def is_icon_exist(self, screen_img, find_img_path, offset, threshold=0.8):
        """
        匹配界面icon
        """
        # 转换成灰度图，便于快速查找
        screen_grey = cv2.cvtColor(screen_img, cv2.COLOR_BGR2GRAY)
        # ImageWindow.show(screen_grey)
        # time.sleep(30)

        # 获取图标图片
        find_img = cv2.imread(find_img_path)
        find_grey = cv2.cvtColor(find_img, cv2.COLOR_BGR2GRAY)
        # ImageWindow.show(find_grey)
        # time.sleep(30)

        # 匹配界面
        match_result = cv2.matchTemplate(screen_grey, find_grey, cv2.TM_CCOEFF_NORMED)
        match_result_where = np.where(match_result >= threshold)
        locations = list(zip(*match_result_where[::-1]))

        if len(locations) > 0:
            loc = (0, 0)
            for item in locations:
                if item[0] > 0 and item[1] > 0:
                    loc = (item[0] + offset[0], item[1] + offset[1])
                    return True, loc
        else:
            return False, (0, 0)
